package graduation.project.testcase.strategy;

import graduation.project.body.OriginExpression;
import graduation.project.body.TestCase;
import graduation.project.body.TestCases;
import graduation.project.exception.NonExpressionException;

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class CUTPNFPGenerator implements TestSetGenerator {

	public TestCases generateTestCases(String expression, int testCaseNumber) {
		try {
			OriginExpression originEx;
			originEx = new OriginExpression(expression);
			return generateTestCases(originEx, testCaseNumber);
		} catch (NonExpressionException e) {
			System.out.println("the expression is not valid boolean expression");
			e.printStackTrace();
		}
		return null;
	}

	public TestCases generateTestCases(OriginExpression expression,
			int testCaseNumber) {
		
		TestCases result = new TestCases(expression.getExpression(), expression.getModel(), "CUTPNFP");
		LinkedHashSet<TestCase> testSet = new LinkedHashSet<TestCase>();
		
		int[][] utpSet = expression.getUtpSet();
		int[][][] nfpSet = expression.getNfpSet();
		
//		int[] utpSelected;
//		int size;
		
		int count = 0;
		boolean isFound = false;
		int[] nfpSelected;
		String tempStr;
		for(int i = 0; i < nfpSet.length; i++){
			count = 0;
			nfpSelected = new int[nfpSet[i].length];
			for(int j = 0; j < nfpSelected.length; j++)
				nfpSelected[j] = -2;
			
			for(int j = 0; j < utpSet[i].length; j++){
				int utpSe = utpSet[i][j];
				for(int k  = 0; k <nfpSet[i].length; k++){
					if(nfpSelected[k] == -1)
						continue;
					
					for(int n = 0; n < nfpSet[i][k].length; n++){
						tempStr = Integer.toBinaryString((utpSe | nfpSet[i][k][n]) - (utpSe & nfpSet[i][k][n])).replaceAll("0", "");
						if(tempStr.length() == 1){
							count++;
							isFound = true;
							nfpSelected[k] = -1;
							testSet.add(new TestCase(nfpSet[i][k][n], false));
							break;
						}
					}
					if(count >= nfpSet[i].length)
						break;
				}
				if(isFound){
					isFound = false;
					testSet.add(new TestCase(utpSe, true));
				}
				if(count >= nfpSet[i].length)
					break;
			}
		}
		ArrayList<TestCase> set = new ArrayList<TestCase>();
		set.addAll(testSet);
		result.setTestSet(set);
		return result;
	}
}
